package com.outsourcing.bottle.util;

import java.io.File;

import android.content.Context;

import com.outsourcing.bottle.domain.UrlConfig;

public class ImageFileCache {
    
    private File cacheDir;
    
    public ImageFileCache(Context context, String path){
        //Find the dir to save cached images
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
            cacheDir = new File(android.os.Environment.getExternalStorageDirectory(), path);
        else
            cacheDir = context.getCacheDir();
        if(!cacheDir.exists())
            cacheDir.mkdirs();
    }
    
    public File getFile(String url){
        //I identify images by hashcode. Not a perfect solution, good for the demo.
//        String filename=String.valueOf(url.hashCode());
        //Another possible solution (thanks to grantland)
//        String filename = URLEncoder.encode(url);
    	String filename = convertUrlToFileName(url);
        File f = new File(cacheDir, filename);
        return f;
        
    }
    
    private String convertUrlToFileName(String url) {
		String filename = url;
		if (filename.indexOf("?") != -1) {
			filename = filename.substring(0, filename.indexOf("?"));
		}
		filename = filename.replace(UrlConfig.url, "");
		filename = filename.replace("/", ".");
		String suffix = filename.substring(filename.lastIndexOf(".") + 1, filename.length());
		if (suffix.equals("jpg")) {
			filename = filename.replace("jpg", "dat");
		} else if (suffix.equals("gif")) {
			filename = filename.replace("gif", "dat");
		} else if (suffix.equals("jpeg")) {
			filename = filename.replace("jpeg", "dat");
		} else if (suffix.equals("png")) {
			filename = filename.replace("png", "dat");
		}
		return filename;
	}
    
    public void clear(){
        File[] files = cacheDir.listFiles();
        if (files == null)
            return;
        for (File f:files)
            f.delete();
    }

}